import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import copy from 'rollup-plugin-copy'
import config from "./package.json"
import {basename, extname, resolve} from "path"
import * as fs from "fs";
import * as path from "node:path";

// 动态获取 src/content 文件夹下的所有 TypeScript 文件
const contentFilesArray = fs.readdirSync(resolve('src/content'))
    .filter(file => file.endsWith('.ts'))
    .map(file => {
      const name = path.basename(file,path.extname(file));
      return {[name]:resolve(`src/content/${file}`)}
    });
const contentFiles = Object.assign({}, ...contentFilesArray);
export default defineConfig({
  root:"src/",
  plugins: [
    react(),
    copy({
      targets:[
        {src:"manifest.json",dest:config.name},
        {src:"src/icons/**",dest:resolve(config.name,"icons")},
      ],
      hook: 'writeBundle' // 确保在打包输出阶段执行
    })
  ],
  server:{
    host:'0.0.0.0',
    port:7890,
    open:'/popup/index.html',
  },
  build:{
    outDir:resolve(__dirname,config.name),
    emptyOutDir:true,
    rollupOptions:{
      input:{
        popup:resolve(__dirname,"src/popup/index.html"),
        contentPage:resolve(__dirname,"src/popup/index.html"),
        background:resolve(__dirname,"src/background/service-worker.ts"),
        ...contentFiles
      },
      output:{
        assetFileNames:"asstes/[name]-[hash].[ext]",
        chunkFileNames:"js/[name]-[hash].js",
        entryFileNames:(chunk)=>{
          const fileFolder=chunk.name
          const facadeModuleId=chunk.facadeModuleId as string
          const baseName = basename(facadeModuleId, extname(facadeModuleId))
          const saveArr = ['contentPage', 'background','popup']
          const noBuildFile = ['common']
          const noBuildFolder = ['content']
          const folder=path.basename(path.dirname(facadeModuleId))
          if (saveArr.includes(folder)){
            return `${folder}/${baseName}.js`
          }else if (noBuildFolder.includes(folder)){
            return `content/${baseName}.js`
          }else {
            return `${baseName}/[name].js`
          }
        },
        name:'[name].js'
      }
    }
  }
})
